package linkeklist;

import java.util.LinkedList;

public class josephuTest {
	public static void main(String[] args) {
		int nums = 11;
		int start = 3;
		int countNum = 4;
		CircleLinkedList circleLinkedList = new CircleLinkedList();
		circleLinkedList.addNode2(nums);
		circleLinkedList.showNode2();
		System.out.println("\n\n");
		circleLinkedList.popNode(nums, start, countNum);
	}
}

class Node2 {
	private int no;
	private Node2 next;

	public Node2(int no) {
		this.no = no;
	}

	public int getNo() {
		return no;
	}

	public void setNo(int no) {
		this.no = no;
	}

	public Node2 getNext() {
		return next;
	}

	public void setNext(Node2 next) {
		this.next = next;
	}
}

class CircleLinkedList {
	Node2 first = new Node2(-1);

	public void addNode2(int nums) {
		if (nums < 1) {
			System.out.println("不合法");
			return;
		}
		Node2 cur = null;
		for (int i = 1; i <= nums; i++) {
			Node2 node = new Node2(i);
			if (i == 1) {
				first = node;
				cur = node;
				node.setNext(first);
			}
			cur.setNext(node);
			node.setNext(first);
			cur = cur.getNext();
		}
	}

	public void showNode2() {
		if (first == null) {
			System.out.println("链表为空");
			return;
		}

		Node2 cur = first;
		while (true) {
			System.out.printf("节点编号 %d\n", cur.getNo());
			if (cur.getNext() == first) {
				break;
			}
			cur = cur.getNext();
		}
	}

	public void popNode(int nums, int start, int countNum) {
		if (nums < 1 || start < 1 || start > nums || countNum < 0) {
			System.out.println("参数有误");
			return;
		}
		Node2 end = first;
		while (end.getNext() != first) {
			end = end.getNext();
		}
		for (int i = 0; i < start - 1; i++) {
			end = end.getNext();
			first = first.getNext();
		}
		while (end != first) {
			for (int j = 0; j < countNum - 1; j++) {
				end = end.getNext();
				first = first.getNext();
			}
			System.out.println("弹出节点" + first.getNo());
			end.setNext(first.getNext());
			first = first.getNext();
		}
		System.out.println("最后留下节点" + first.getNo());

	}
}
